<template>
  <d2-container class="page">
    <el-dialog
      width="1024px"
      title="分销详情"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <!-- <el-button type="primary" size="mini" @click="getList2()">刷新</el-button> -->
      <el-button type="success" size="mini" @click="payBill()">结账</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData2"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
     
      <el-table-column label="订单号" width="200">
        <template slot-scope="scope">{{ scope.row.orderCode }}</template>
      </el-table-column>
      <el-table-column label="订单金额">
        <template slot-scope="scope">{{ scope.row.orderAmount | fen2yuan }}</template>
      </el-table-column>
      <el-table-column label="返佣人">
        <template slot-scope="scope">{{ scope.row.buyerName }}</template>
      </el-table-column>
      <el-table-column label="分销级别">
        <template slot-scope="scope">{{ scope.row.relationLevel }}</template>
      </el-table-column>
      <el-table-column label="返佣比例(%)" width="100">
        <template slot-scope="scope">{{ scope.row.ratio }}</template>
      </el-table-column>
      <el-table-column label="佣金">
        <template slot-scope="scope">{{ scope.row.amount | fen2yuan }}</template>
      </el-table-column>
      <el-table-column label="支付状态">
        <template slot-scope="scope">{{ scope.row.settleFlag | payStatus }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.createTime | format2DateTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column label="支付时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.settleDate | format2DateTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">{{ scope.row.settleNode}}</template>
      </el-table-column>
      <!-- <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showDetailDlg(scope.row)">详情</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <br>
    <el-pagination
      background=""
      layout="prev, pager, next"
      :page-size="25"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button v-if="createOrEdit=='新建'" type="primary" @click="handleCreateNew('form')">确 定</el-button>
        <el-button v-else type="primary" @click="handleCreateNew('form')">修 改</el-button> -->
      </div>
    </el-dialog>

    <!-- <el-button type="primary" size="mini" @click="showCreateDlg('form')">新建</el-button> -->
    <el-button type="primary" size="mini" @click="getList()">刷新</el-button>
    <el-divider></el-divider>
    <el-table
      stripe
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号"></el-table-column>
      <!-- <el-table-column label="id" width="120">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>-->
     
      <el-table-column label="分销员">
        <template slot-scope="scope">{{ scope.row.realName }}</template>
      </el-table-column>
      <!-- <el-table-column label="分享规则">
        <template slot-scope="scope">{{ scope.row.distributionName }}</template>
      </el-table-column> -->
      <el-table-column label="订单合计金额">
        <template slot-scope="scope">{{ scope.row.orderAmount | fen2yuan }}</template>
      </el-table-column>
      <el-table-column label="订单数">
        <template slot-scope="scope">{{ scope.row.orderCount }}</template>
      </el-table-column>
      <el-table-column label="佣金合计金额">
        <template slot-scope="scope">{{ scope.row.amount | fen2yuan }}</template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" width="200">
        <template
          slot-scope="scope"
        >{{ scope.row.createTime | format2DateTime('{y}-{m}-{d} {h}:{m}:{s}') }}</template>
      </el-table-column> -->
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="primary" @click="showEditDlg(scope.row)" icon="el-icon-edit"></el-button> -->
          <el-button size="mini" type="primary" @click="showDetailDlg(scope.row)">详情</el-button>
          <!-- <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
          ></el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
      background=""
      layout="prev, pager, next"
      :page-size="25"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </d2-container>
</template>

<script>
import * as distribution from "@/api/shop.distribution";

export default {
  components: {},
  data() {
    return {
      treeData: null,
      dialogFormVisible2: false,
      props: {
        label: "nickname",
        children: "children",
        isLeaf: "leaf"
      },
      fileList: [],
      tableData: [],
      tableData2: [],
      multipleSelection: [],
      dialogFormVisible: false,
      form: {},
      formLabelWidth: "150px",
      dialogVisible: false,
      createOrEdit: "",
      listQuery: {
        pageStart: 1,
        pageSize: 25
      },
      total: 0
    };
  },
  filters: {
    payStatus: function(status) {
      if(status == 0)
        return "未支付";
      if(status == 1)
        return "已支付";
    },

    fen2yuan: function(fen) {
      return fen / 100;
    },

    format2DateTime: function(time, cFormat) {
      time = Date.parse(new Date(time));
      if (arguments.length === 0) {
        return null;
      }

      if ((time + "").length === 10) {
        time = +time * 1000;
      }

      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date;
      if (typeof time === "object") {
        date = time;
      } else {
        date = new Date(parseInt(time));
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a")
          return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
        if (result.length > 0 && value < 10) {
          value = "0" + value;
        }
        return value || 0;
      });
      return timeStr;
    }
  },
  mounted() {
    this.getList();
    this.$route.meta.title = "对账单";
  },
  methods: {
    payBill() {
      console.log(this.multipleSelection);
      let ids = [];
      let sumMoney = 0;
      let count = 0;
      this.multipleSelection.forEach(element => {
        if(element.settleFlag == 0) {
          ids.push(element.id);
          sumMoney += element.amount;
          count++;
        }
      });

      if(sumMoney == 0) {
        this.$notify({
          title: "提示",
          message: "已经全部支付",
          type: "error",
          duration: 2000
        });
        return;
      }

      this.$prompt(count + " 笔订单, 佣金: " + sumMoney / 100 + ', 确认支付么？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
            if(value == null) {
              this.$message({
              type: 'info',
              message: '备注信息不能为空'
            });  
            return;
          }
          distribution.settleCommissionByIds({ids: ids, remarks: value}).then(resp => {
            console.log(resp);
            if(resp.success) {
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
                duration: 2000
              });
            }
          });
        }).catch(() => {
            
        });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    showDetailDlg(row) {
      this.dialogFormVisible = true;
      this.form = row;

      distribution.distributionDetail({userId: row.id, pageStart:1, pageSize:25}).then(resp => {
        console.log(resp);
        this.tableData2 = resp.records;
      });
    },

    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ nickname: "根节点", id: this.form.personnelId }]);
      }

      if (node.level > 2)
        return resolve();
      
      distribution.getPersonnelByParentId({shopId: 336, id: node.data.id, pageStart:1, pageSize:25}).then(resp => {
        console.log(resp);
        resolve(resp.records)
      });

    },

    handleSizeChange(e) {
      console.log("handleSizeChange", e);
    },

    handleCurrentChange(e) {
      console.log("handleCurrentChange", e);
      this.listQuery.pageStart = e;
      this.getList();
    },

    showCreateDlg(formName) {
      this.dialogFormVisible = true;
      this.createOrEdit = "新建";
      // this.$refs[formName].resetFields();
    },

    showEditDlg(row) {
      this.dialogFormVisible = true;
      this.createOrEdit = "编辑";
      this.form = row;
    },

    handleUploadSuccess(response, file, fileList) {
      console.log(response);
      if (response.success) this.downloadPath = response.downloadPath;
    },

    handleCreateNew(formName) {
      let that = this;

      const set = that.$refs;
      set[formName].validate(valid => {
        if(this.form.defaultFlag)
          this.form.defaultFlag = 1;
        else
          this.form.defaultFlag = 0;

        distribution.createOrEditDistributionRule(this.form).then(resp => {
          that.dialogFormVisible = false;
          that.getList();

          that.$notify({
            title: "成功",
            message: "操作成功",
            type: "success",
            duration: 2000
          });
        });
      });
    },

    getList() {
      distribution.fetchList4Statement(this.listQuery).then(response => {
        this.tableData = response.records;
        this.total = response.total;
      });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    handleDelete(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        distribution
          .deleteDistributionRule(row.id)
          .then(() => {
            this.getList();
            this.$notify({
              title: "提示",
              message: "操作成功",
              type: "success",
              duration: 2000
            });
          })
          .catch(() => {
            this.$notify({
              title: "提示",
              message: "操作失败",
              type: "error",
              duration: 2000
            });
          });
      });
    }
  }
};
</script>
